
package com.meixiaoliang.portal.core.util;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.apache.commons.lang3.StringUtils;

import com.meixiaoliang.portal.core.exception.ValidateException;

/**
 * 入参校验工具类
 *
 * @author mei.xiaoliang@qq.com
 */
public class ValidateUtil {

    public static void valid(Object obj) {

        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

        Set<ConstraintViolation<Object>> violations = validator.validate(obj);
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation<Object> violation : violations) {
            if (StringUtils.isNotBlank(sb)) {
                sb.append(",");
            }
            sb.append(violation.getMessage());
        }

        if (StringUtils.isNotBlank(sb)) {
            throw new ValidateException(sb.toString());
        }

    }

    /**
     * 对象空断言
     *
     * @param obj     判断对象
     * @param message 错误信息
     */
    public static void notNull(Object obj, String message) {
        if (null == obj) {
            throw new ValidateException(message);
        }
    }

    /**
     * 字符串空断言
     *
     * @param string  判断对象
     * @param message 错误信息
     */
    public static void notBlank(String string, String message) {
        if (StringUtils.isBlank(string)) {
            throw new ValidateException(message);
        }
    }

}